#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <math.h>

int my_atoi(const char* str)
{
    assert(str);
    int flag = 0;
    bool sign = true;
    int count = 0;
    int sum = 0;
    while (isspace(*str))
    {
        str++;
    }
    if ((*str == '\0') || (!(isdigit(*str)) && (*str != '+') && (*str != '-')))
    {
        return 0;
    }
    while ((*str == '+') || (*str == '-'))
    {
        if (flag == 1)
        {
            return 0;
        }
        flag = 1;
        if (*str == '-')
        {
            sign = false;
        }
        str++;
    }
    while (isdigit(*str))
    {
        count++;
        str++;
    }
    for (int k = 1;k <= count;k++)
    {
        sum += ((*(str - k) - '0') * (int)pow(10, k - 1));
    }
    if (count > 0)
    {
        if (sign == true)
        {
            return sum;
        }
        else
        {
            return (-1) * sum;
        }
    }
    return 0;
}

int main()
{
    char str1[] = "12345";    // 正数
    char str2[] = "-6789";    // 负数
    char str3[] = "   +456";  // 前面有空格
    char str4[] = "12abc34";  // 包含非数字字符
    char str5[] = "abc123";   // 非数字开头
    char str6[] = "";         // 空字符串
    char str7[] = "  ";            // 仅有空格字符
    char str8[] = "  +-321";  // 两个符号
    char str9[] = "  +a321";  // 符号后面又出现非数字

    int num1 = my_atoi(str1);
    int num2 = my_atoi(str2);
    int num3 = my_atoi(str3);
    int num4 = my_atoi(str4);
    int num5 = my_atoi(str5);
    int num6 = my_atoi(str6);
    int num7 = my_atoi(str7);
    int num8 = my_atoi(str8);
    int num9 = my_atoi(str9);

    printf("字符串 \"%s\" 转换为整数: %d\n", str1, num1);
    printf("字符串 \"%s\" 转换为整数: %d\n", str2, num2);
    printf("字符串 \"%s\" 转换为整数: %d\n", str3, num3);
    printf("字符串 \"%s\" 转换为整数: %d\n", str4, num4);
    printf("字符串 \"%s\" 转换为整数: %d\n", str5, num5);
    printf("字符串 \"%s\" 转换为整数: %d\n", str6, num6);
    printf("字符串 \"%s\" 转换为整数: %d\n", str7, num7);
    printf("字符串 \"%s\" 转换为整数: %d\n", str8, num8);
    printf("字符串 \"%s\" 转换为整数: %d\n", str9, num9);
    return 0;
}